<template>
  <div class="main">
    <div class="top">
      用户登录 / <span>USER LOGIN</span>
    </div>
    <a-form
      id="formLogin"
      class="user-layout-login"
      ref="formLogin"
      :form="form"
      @submit="handleSubmit"
    >
      <a-form-item>
        <a-input
          size="large"
          type="text"
          placeholder="请输入手机号"
          v-decorator="[
            'phone',
            {rules: [{ required: true, message: '请输入手机号' },{validator: mobilephoneValidate}], validateTrigger: 'change'}
          ]"
        >
        </a-input>
      </a-form-item>

      <a-form-item class="">
        <div class="codeBox">
          <a-input
            class="codeInput"
            size="large"
            placeholder="请输入验证码"
            v-decorator="[
              'code',
              {rules: [{ required: true, message: '请输入验证码' }], validateTrigger: 'blur'}
            ]"
          >
          </a-input>
          <a-button v-if="!sendMsgDisabled" @click="getCode" class="codeBtn" :disabled="!isPhone">获取验证码</a-button>
          <a-button v-if="sendMsgDisabled" class="codeBtn" disabled>{{ time }}秒后获取</a-button>
        </div>
      </a-form-item>

      <a-form-item style="margin-top:24px">
        <a-button
          size="large"
          type="primary"
          htmlType="submit"
          class="login-button"
          :loading="state.loginBtn"
          :disabled="state.loginBtn"
        >登录</a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script>
import { getVerificationCode } from '@/api/login'
import { mapActions } from 'vuex'
import { timeFix } from '@/utils/util'
import storage from 'store'
import { ACCESS_TOKEN } from '@/store/mutation-types'
export default {
  components: {
  },
  data () {
    return {
      isPhone: false,
      isLoginError: false,
      form: this.$form.createForm(this),
      state: {
        loginBtn: false
      },
      time: 60, // 发送验证码倒计时
      sendMsgDisabled: false
    }
  },
  created () {

  },
  methods: {
    ...mapActions(['Login', 'Logout']),
    getCode () {
      const phone = this.form.getFieldValue('phone')
      if (this.testMobilephone(phone)) {
        getVerificationCode({
          phone,
          terminal_type: 'PC',
          codeType: 2
        })
        .then(res => {
          this.sendMsgDisabled = true
          const interval = window.setInterval(() => {
            if ((this.time--) <= 0) {
                this.time = 60
                this.sendMsgDisabled = false
                window.clearInterval(interval)
            }
          }, 1000)
        })
      }
    },
    testMobilephone (str) {
      const regex = /^1[3456789]\d{9}$/
      if (!regex.test(str)) {
        return false
      } else {
        return true
      }
    },
    mobilephoneValidate (rule, value, callback) {
      // 主要就是添加一个对undefined和空串的判断
      if (typeof (value) === 'undefined' || value === '') {
        this.isPhone = false
        callback()
      } else {
        if (!this.testMobilephone(value)) {
          this.isPhone = false
          callback(new Error('请输入正确手机格式'))
        } else {
          this.isPhone = true
          callback()
        }
      }
    },
    handleSubmit (e) {
      e.preventDefault()
      const {
        form: { validateFields },
        state,
        Login
      } = this

      state.loginBtn = true

      const validateFieldsKey = ['phone', 'code']

      validateFields(validateFieldsKey, { force: true }, (err, values) => {
        if (!err) {
          console.log('login form', values)
          const loginParams = { ...values }
           Login(loginParams)
            .then((res) => this.loginSuccess(res))
            .finally(() => {
              state.loginBtn = false
            })
        } else {
          setTimeout(() => {
            state.loginBtn = false
          }, 600)
        }
      })
    },
    loginSuccess (res) {
      // 判断是申报端还是管理端登录
      console.log('loginSuccess---', res)
      let loginType = res.loginType || 'MANAGEMENT_PC'
      if (loginType == 'DECLARATION_PC') {
        // 申报端 设置token 跳转申报端
        localStorage.setItem('token', res.token)
        window.location = '/grade-evaluation-declaration/'
      } else {
        // 管理端
        // token有效期10个小时，则cookie保存9小时
        storage.set(ACCESS_TOKEN, res.token, new Date().getTime() + 9 * 60 * 60 * 1000)
        this.$store.commit('SET_TOKEN', res.token)
        this.$router.push({ path: '/' })
        // 延迟 1 秒显示欢迎信息
        setTimeout(() => {
          this.$notification.success({
            message: '欢迎',
            description: `${timeFix()}，欢迎回来`
          })
        }, 1000)
        this.isLoginError = false
      }
    }
  }
}
</script>

<style lang="less" scoped>
.main {
  width: 100%;
  height: 100%;
  .flex-center-vertical();
  .top {
    width: .vw(450) [ @return];
    color: #1165E2;
    font-size: .vw(36) [ @return];
    margin-bottom: .vh(60) [ @return];
    padding-left: .vw(15) [ @return];
    span {
      font-size: .vw(20) [ @return];
    }
  }
  .user-layout-login {
    :deep(.ant-form-item) {
      margin-bottom: 22px;
      .ant-input {
        font-size: .vw(21) [ @return];
        width: .vw(458) [ @return];
        height: .vh(72) [ @return];
        line-height: .vh(72) [ @return];
        border-radius: .vh(72) [ @return];
        padding: 0 0 0 .vw(35) [ @return];
        background: rgba(116, 162, 241,0.24 );
        &::placeholder {
          color: #749CE1;
        }
      }
      .ant-form-explain {
        position: absolute;
        bottom: -22px;
        margin-bottom: 0;
      }
    }
    .codeBox {
      .flex-between();
      .codeInput {
        width: .vw(318) [ @return];
        border-top-right-radius: 0;
        border-bottom-right-radius: 0;
      }
      .codeBtn {
        font-size: .vw(18) [ @return];
        width: .vw(140) [ @return];
        height: .vh(72) [ @return];
        border-radius: .vh(72) [ @return];
        border-top-left-radius: 0;
        border-bottom-left-radius: 0;
        .flex-center();
      }
    }
    .login-button {
      font-size: .vw(28) [ @return];
      width: .vw(458) [ @return];
      height: .vh(72) [ @return];
      border-radius: .vh(72) [ @return];
      background: rgba(24, 144, 255, 0.92);
      margin-top: .vh(58) [ @return];
    }
  }
}
</style>
